package peter.controller;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import peter.models.skill.Skill;
import peter.models.skill.SkillRepository;

@Controller
// @ComponentScan
@RequestMapping("/skill")
public class SkillController {
    @Autowired // This means to get the bean called userRepository
    private SkillRepository skillRepository;

    @RequestMapping("/main")
    public String main(@RequestParam(value = "name", required = false, defaultValue = "World") String name,
                    Model model) {
        Iterable<Skill> skills = this.skillRepository.findAll(new Sort(Direction.DESC, "favorite", "weight", "level"));
        model.addAttribute("skills", skills);
        return "skill/main";
    }

    @RequestMapping("/save")
    public @ResponseBody Map<String, String> save(@RequestParam(required = false) Integer id, @RequestParam String name, @RequestParam Integer value,
                    Model model) {
        System.out.println(">>>> " + id + ", " + name + ", " + value);
        Skill skill = null;

        if(null == id) {
            skill = new Skill();
            skill.setId(id);
        }
        else {
            skill = this.skillRepository.findOne(id);
            System.out.println(">>> " + skill.toString());
        }

        System.out.println("<<< " + skill.toString());
        skill.setName(name);
        skill.setLevel(value);
        this.skillRepository.save(skill);
        Map<String, String> result = new HashMap<String, String>();
        result.put("status", "200");
        return result;
    }

    /*
    @RequestMapping("/greeting")
    public String greeting(@RequestParam(value = "name", required = false, defaultValue = "World") String name,
                    Model model) {
        System.out.println(">>>>>> peter");
        // Iterable<Skill> skills = skillRepository.findAll();
        // model.addAttribute("skills", skills);
        // return "main";
        return "main";
    }
    */
}
